package com.chen.base.utils;


import com.chen.root.constant.ThreadPoolCons;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Supplier;

/**
 * @author: Long
 * @date: 2023/6/10 20:20
 **/
public class AsyncUtil {

    /**
     * 执行异步, 默认使用 commonThreadPoolExecutor线程池
     * @param runnable 业务逻辑
     * @return 异常执行情况
     */
    public static CompletableFuture<Void> runAsync(Runnable runnable){
        Executor executor = SpringContextHolder.getBean(ThreadPoolCons.COMMON_THREAD_POOL);
        return CompletableFuture.runAsync(runnable, executor);
    }

    /**
     * 执行异步, 默认使用 commonThreadPoolExecutor线程池
     * @param supplier 业务逻辑
     * @return 异常执行情况
     */
    public static <U> CompletableFuture<U> runAsync(Supplier<U> supplier){
        Executor executor = SpringContextHolder.getBean(ThreadPoolCons.COMMON_THREAD_POOL);
        return CompletableFuture.supplyAsync(supplier, executor);
    }

    /**
     * 阻塞主线程，直到所有线程全部执行完
     */
    public static void allOf(CompletableFuture<?>... cfs){
        CompletableFuture.allOf(cfs).thenAccept(data -> {}).join();
    }
}
